import asyncio
import aiohttp
import json
import os
from lightrag.llm.openai import openai_embed

async def debug_embedding_api():
    """详细调试硅基流动的embedding API，使用LightRAG的配置方式"""
    
    # 使用与LightRAG相同的配置参数
    model = os.getenv("EMBEDDING_MODEL", "BAAI/bge-m3")
    base_url = os.getenv("EMBEDDING_BINDING_HOST", "https://api.siliconflow.cn/v1/embeddings")
    api_key = os.getenv("EMBEDDING_BINDING_API_KEY") or os.getenv("OPENAI_API_KEY", "sk-xxjzwmnsxdodiqnfwtxkizjnplmexrpfomqzetjaeppvvrnl")
    
    print("=== LightRAG配置参数 ===")
    print(f"EMBEDDING_MODEL: {model}")
    print(f"EMBEDDING_BINDING_HOST: {base_url}")
    print(f"API_KEY: {api_key[:20]}..." if api_key else "API_KEY: None")
    
    # 测试文本
    test_texts = ["Silicon flow embedding online: fast, affordable, and high-quality embedding services."]
    
    print(f"\n=== 测试文本 ===")
    print(f"输入文本: {test_texts}")
    
    print(f"\n=== 使用LightRAG的openai_embed函数 ===")
    try:
        # 使用LightRAG的openai_embed函数
        result = await openai_embed(
            texts=test_texts,
            model=model,
            base_url=base_url,
            api_key=api_key,
        )
        
        print(f"✅ LightRAG openai_embed调用成功!")
        print(f"结果形状: {result.shape}")
        print(f"Embedding维度: {result.shape[1]}维")
        print(f"Embedding前5个值: {result[0][:5]}")
        print(f"Embedding后5个值: {result[0][-5:]}")
        
    except Exception as e:
        print(f"❌ LightRAG openai_embed调用失败: {e}")
        import traceback
        traceback.print_exc()
    
    print(f"\n=== 手动构建请求对比 ===")
    # 手动构建请求进行对比
    url = base_url
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "User-Agent": "LightRAG/1.3.9"
    }
    
    test_data = {
        "model": model,
        "input": test_texts
    }
    
    print(f"请求URL: {url}")
    print(f"请求头: {headers}")
    print(f"请求数据: {json.dumps(test_data, indent=2, ensure_ascii=False)}")
    
    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(url, headers=headers, json=test_data) as response:
                print(f"\n响应状态码: {response.status}")
                print(f"响应头: {dict(response.headers)}")
                
                response_text = await response.text()
                print(f"响应内容: {response_text}")
                
                if response.status == 200:
                    result = json.loads(response_text)
                    if 'data' in result and len(result['data']) > 0:
                        embedding = result['data'][0]['embedding']
                        print(f"\n✅ 手动请求成功!")
                        print(f"Embedding长度: {len(embedding)}")
                        print(f"Embedding维度: {len(embedding)}维")
                        print(f"Embedding前5个值: {embedding[:5]}")
                        print(f"Embedding后5个值: {embedding[-5:]}")
                    else:
                        print("❌ 响应中没有embedding数据")
                else:
                    print(f"❌ API请求失败，状态码: {response.status}")
                    
        except Exception as e:
            print(f"❌ 手动请求异常: {e}")

if __name__ == "__main__":
    asyncio.run(debug_embedding_api()) 